import { ref, onMounted, onUnmounted, Ref } from 'vue'

// 设置 自定义函数
const useClickOutside = (elementRef: Ref<null | HTMLElement>) => {
  const isClickOutside = ref(false)
  // dom节点内容 是否存在
  const handler = (e: MouseEvent) => {
    if (elementRef.value) {
      if (elementRef.value.contains(e.target as HTMLElement)) {
        isClickOutside.value = false
      } else {
        isClickOutside.value = true
      }
    }
  }
  onMounted(() => {
    // 添加监听 点击事件
    document.addEventListener('click', handler)
  })
  // 移除监听 点击事件
  onUnmounted(() => {
    document.removeEventListener('click', handler)
  })
  return isClickOutside
}

// 导出 自定义函数
export default useClickOutside
